#!/usr/bin/env python3
"""
Text2SQL评估系统后端启动脚本
"""
import os
import sys
import subprocess

def check_requirements():
    """检查依赖是否安装"""
    try:
        import flask
        import numpy
        import datasets
        import ragas
        import langchain_openai
        import langchain_huggingface
        print("✓ 所有依赖已安装")
        return True
    except ImportError as e:
        print(f"✗ 缺少依赖: {e}")
        return False

def install_requirements():
    """安装依赖"""
    print("正在安装依赖...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "backend/requirements.txt"])
        print("✓ 依赖安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ 依赖安装失败: {e}")
        return False

def check_env_file():
    """检查环境变量文件"""
    env_file = "backend/.env"
    if not os.path.exists(env_file):
        print("⚠ 未找到 .env 文件，请创建 backend/.env 文件并设置 OPENAI_API_KEY")
        print("参考 backend/env_example.txt 文件")
        return False
    return True

def main():
    """主函数"""
    print("=== Text2SQL评估系统后端启动 ===")
    
    # 检查依赖
    if not check_requirements():
        print("正在安装依赖...")
        if not install_requirements():
            print("依赖安装失败，请手动安装")
            return
    
    # 检查环境变量
    if not check_env_file():
        print("请先配置环境变量文件")
        return
    
    # 启动Flask应用
    print("启动后端服务...")
    os.chdir("backend")
    try:
        subprocess.run([sys.executable, "app.py"])
    except KeyboardInterrupt:
        print("\n服务已停止")
    except Exception as e:
        print(f"启动失败: {e}")

if __name__ == "__main__":
    main()
